<template>
	<div class="user-list">
		<el-card>
			<el-form
				ref="form"
				:model="filterParams"
				:rules="filterForm"
				inline
			>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="filterParams.phone"></el-input>
				</el-form-item>
				<el-form-item label="注册时间" prop="rangeDate">
					<el-date-picker
						v-model="filterParams.rangeDate"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSave" :disabled="loading">查询</el-button>
					<el-button @click="reset" :disabled="loading">重置</el-button>
				</el-form-item>
			</el-form>
		
			<el-table border :data="users" style="width: 100%" v-loading="loading">
				<el-table-column prop="id" label="用户ID" min-width="100">
				</el-table-column>
				<el-table-column prop="portrait" label="头像" min-width="100">
					<template slot-scope="scope">
						<el-avatar
							:size="30"
							:src="
								scope.row.portrait || require('@/assets/default-avatar.png')
							"
						></el-avatar>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="用户名" min-width="240">
				</el-table-column>
				<el-table-column prop="phone" label="手机号" min-width="150">
				</el-table-column>
				<el-table-column prop="createTime" label="注册时间" min-width="150">
					<template slot-scope="scope">
						<span>{{ scope.row.createTime | date }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" min-width="150">
					<template slot-scope="scope">
						<span
							class="status"
							:class="{
								'status-success': scope.row.status === 'ENABLE',
								'status-danger': scope.row.status === 'DISABLE',
							}"
							:title="scope.row.status === 'ENABLE' ? '正常' : '禁用'"
						></span>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="150">
					<template slot-scope="scope">
						<el-button
							v-if="scope.row.status === 'ENABLE'"
							type="text"
							@click="handleForbidden(scope.row)"
							>禁用</el-button
						>
						<el-button type="text" @click="handleAlloc(scope.row)"
							>分配角色</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:disabled="loading"
				:current-page.sync="currentPage"
				:page-sizes="[10, 20, 30, 40]"
				:page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalCount"
			>
			</el-pagination>
		</el-card>

		<el-dialog :title="'分配角色'" width="500px" :visible.sync="dialogVisible">
			<el-select
				v-model="roleIdList"
				multiple
				placeholder="请选择"
				style="width: 100%"
			>
				<el-option
					v-for="item in roles"
					:key="item.id"
					:label="item.name"
					:value="item.id"
				>
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleAllocRole">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { Form } from 'element-ui'
import Vue from 'vue'
import { getUserPages, ForbidUser } from '@/services/user'
import { getAllRoles, allocateUserRoles, getUserRoles } from '@/services/role'

export default Vue.extend({
  name: 'UserList',
  data () {
    return {
      filterParams: {
        phone: '',
        rangeDate: []
      },
      filterForm: {
        phone: [
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      currentPage: 1,
      pageSize: 10,
      users: [],
      totalCount: 10,
      loading: false,
      dialogVisible: false,
      roles: [],
      roleIdList: [],
      currentRole: {}
    }
  },
  created () {
    this.loadUsers()
  },
  methods: {
    reset () {
      (this.$refs.form as Form).resetFields()
      this.loadUsers()
    },
    onSave () {
      console.log(this.filterParams)
      this.loadUsers()
    },
    handleSizeChange (val: number) {
      this.pageSize = val
      this.currentPage = 1
      this.loadUsers()
    },
    handleCurrentChange (val: number) {
      this.currentPage = val
      this.loadUsers()
    },
    async loadUsers () {
      this.loading = true
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        phone: this.filterParams.phone,
        startCreateTime: this.filterParams.rangeDate[0] as string,
        endCreateTime: this.filterParams.rangeDate[1] as string
      }
      const { data } = await getUserPages(params)
      this.loading = false
      console.log(data)
      this.users = data.data.records
      this.totalCount = data.data.total
    },
    handleForbidden (item: { [key: string]: number }) {
      this.$confirm('是否要禁用该用户？', '提示', { type: 'warning' }).then(
        async () => {
          await ForbidUser(item.id)
          this.$message.success('禁用成功')
          this.loadUsers()
        }
      )
    },
    async handleAlloc (role: any) {
      this.currentRole = role

      const { data } = await getAllRoles()
      this.roles = data.data

      const {
        data: { data: userRoles }
      } = await getUserRoles((this.currentRole as any).id)
      this.roleIdList = userRoles.map((item: any) => item.id)
      this.dialogVisible = true
    },
    async handleAllocRole () {
      const params = {
        userId: (this.currentRole as any).id,
        roleIdList: this.roleIdList
      }
      await allocateUserRoles(params)
      this.$message.success('操作成功')
      this.dialogVisible = false
    }
  }
})
</script>

<style lang="scss" scoped></style>
